package com.pug.web.interceptor;

import com.pug.web.interceptor.context.HeaderContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author RenGaoshuai
 * @date 2023/7/6 14:39
 * @description 请求头统一拦截器，将请求头中的信息获取出来，存入到自定义上下文中，以便在其他地方使用
 * 注意：有两种方式
 * 方式1：实现HandlerInterceptor接口
 * 方式2：继承HandlerInterceptorAdapter
 *
 * 拦截器编写王城后，一定要配置到项目中，否则不生效
 */
@Component
@Slf4j
public class HeaderContextInterceptor implements HandlerInterceptor {


    private static final String CLIENT_ID = "clientId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //初始化上下文
        initHandlerContext(request);
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //本次请求结束，清空上下文
        HeaderContext.cleanContext();
    }


    /**
     * 初始化上下文
     *
     * @param request 请求
     */
    private void initHandlerContext(HttpServletRequest request) {

        String clientId = request.getHeader(CLIENT_ID);
        log.info(">>>>>>>拦截到请求相关请求头<<<<<<<<，clientId：【{}】", clientId);

        //构建上下文信息
        new HeaderContext.HeaderContextBuild()
                .clientId(clientId)
                .build();

    }
}
